package com.skt.casdemo.service;

import java.util.Random;

import com.skt.casdemo.R;
import com.skt.casdemo.widget.MyWidgetProvider;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class UpdateWidgetService2 extends Service{
	private static final String LOG = "com.skt.casdemo";

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Log.i(LOG, "Called");
		
		//create some random data
		
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
		
		int[] allwidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
		ComponentName thisWidget = new ComponentName(getApplicationContext(), MyWidgetProvider.class);
		int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
		
		Log.w(LOG, "From Intent" + String.valueOf(allwidgetIds.length));
		Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length));
		
		for (int widgetId : allwidgetIds){
			//create some random data
			int number = (new Random().nextInt(1000));
			
			RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.widget_layout_test2);
			
			Log.w("WidgetExample", String.valueOf(number));
			
			//set the text
			remoteViews.setTextViewText(R.id.msgContents, "Random: " + String.valueOf(number));
			//remoteViews.setTextViewText(R.id.update, "viewDetails");
			//remoteViews.setTextViewText(R.id.update, "viewDetails");
			
			//Register an onClickListener
			Intent clickIntent = new Intent(this.getApplicationContext(), MyWidgetProvider.class);
			
			clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allwidgetIds);
			
			PendingIntent pendingIntent1 = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			
			remoteViews.setOnClickPendingIntent(R.id.msgContents, pendingIntent1);
			remoteViews.setOnClickPendingIntent(R.id.viewDetail, pendingIntent2);
			remoteViews.setOnClickPendingIntent(R.id.viewMessage, pendingIntent3);
			appWidgetManager.updateAppWidget(widgetId, remoteViews);
		}
		
		stopSelf();
		
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}
